{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Copyright (C) 2016 - 2019 Pinard Liu(liujianping-ok@163.com)\n",
    "\n",
    "https://www.cnblogs.com/pinard\n",
    "\n",
    "Permission given to modify the code as long as you keep this declaration at the top\n",
    "\n",
    "scikit-learn随机森林调参小结 https://www.cnblogs.com/pinard/p/6160412.html"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "d:\\users\\pinard.liu\\appdata\\local\\programs\\python\\python36\\lib\\site-packages\\sklearn\\cross_validation.py:41: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.\n",
      "  \"This module will be removed in 0.20.\", DeprecationWarning)\n",
      "d:\\users\\pinard.liu\\appdata\\local\\programs\\python\\python36\\lib\\site-packages\\sklearn\\grid_search.py:42: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. This module will be removed in 0.20.\n",
      "  DeprecationWarning)\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.grid_search import GridSearchCV\n",
    "from sklearn import cross_validation, metrics\n",
    "\n",
    "import matplotlib.pylab as plt\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0    19680\n",
       "1      320\n",
       "Name: Disbursed, dtype: int64"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train = pd.read_csv('train_modified.csv')\n",
    "target='Disbursed' # Disbursed的值就是二元分类的输出\n",
    "IDcol = 'ID'\n",
    "train['Disbursed'].value_counts() "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "x_columns = [x for x in train.columns if x not in [target, IDcol]]\n",
    "X = train[x_columns]\n",
    "y = train['Disbursed']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.98005\n",
      "AUC Score (Train): 0.999833\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "d:\\users\\pinard.liu\\appdata\\local\\programs\\python\\python36\\lib\\site-packages\\sklearn\\ensemble\\forest.py:453: UserWarning: Some inputs do not have OOB scores. This probably means too few trees were used to compute any reliable oob estimates.\n",
      "  warn(\"Some inputs do not have OOB scores. \"\n",
      "d:\\users\\pinard.liu\\appdata\\local\\programs\\python\\python36\\lib\\site-packages\\sklearn\\ensemble\\forest.py:458: RuntimeWarning: invalid value encountered in true_divide\n",
      "  predictions[k].sum(axis=1)[:, np.newaxis])\n"
     ]
    }
   ],
   "source": [
    "rf0 = RandomForestClassifier(oob_score=True, random_state=10)\n",
    "rf0.fit(X,y)\n",
    "print (rf0.oob_score_)\n",
    "y_predprob = rf0.predict_proba(X)[:,1]\n",
    "print (\"AUC Score (Train): %f\" % metrics.roc_auc_score(y, y_predprob))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "([mean: 0.80681, std: 0.02236, params: {'n_estimators': 10},\n",
       "  mean: 0.81600, std: 0.03275, params: {'n_estimators': 20},\n",
       "  mean: 0.81818, std: 0.03136, params: {'n_estimators': 30},\n",
       "  mean: 0.81838, std: 0.03118, params: {'n_estimators': 40},\n",
       "  mean: 0.82034, std: 0.03001, params: {'n_estimators': 50},\n",
       "  mean: 0.82113, std: 0.02966, params: {'n_estimators': 60},\n",
       "  mean: 0.81992, std: 0.02836, params: {'n_estimators': 70}],\n",
       " {'n_estimators': 60},\n",
       " 0.8211334476626017)"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "param_test1 = {'n_estimators':[10,20,30,40,50,60,70]}\n",
    "gsearch1 = GridSearchCV(estimator = RandomForestClassifier(min_samples_split=100,\n",
    "                                  min_samples_leaf=20,max_depth=8,max_features='sqrt' ,random_state=10), \n",
    "                       param_grid = param_test1, scoring='roc_auc',cv=5)\n",
    "gsearch1.fit(X,y)\n",
    "gsearch1.grid_scores_, gsearch1.best_params_, gsearch1.best_score_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "([mean: 0.79379, std: 0.02347, params: {'max_depth': 3, 'min_samples_split': 50},\n",
       "  mean: 0.79339, std: 0.02410, params: {'max_depth': 3, 'min_samples_split': 70},\n",
       "  mean: 0.79350, std: 0.02462, params: {'max_depth': 3, 'min_samples_split': 90},\n",
       "  mean: 0.79367, std: 0.02493, params: {'max_depth': 3, 'min_samples_split': 110},\n",
       "  mean: 0.79387, std: 0.02521, params: {'max_depth': 3, 'min_samples_split': 130},\n",
       "  mean: 0.79373, std: 0.02524, params: {'max_depth': 3, 'min_samples_split': 150},\n",
       "  mean: 0.79378, std: 0.02532, params: {'max_depth': 3, 'min_samples_split': 170},\n",
       "  mean: 0.79349, std: 0.02542, params: {'max_depth': 3, 'min_samples_split': 190},\n",
       "  mean: 0.80960, std: 0.02602, params: {'max_depth': 5, 'min_samples_split': 50},\n",
       "  mean: 0.80920, std: 0.02629, params: {'max_depth': 5, 'min_samples_split': 70},\n",
       "  mean: 0.80888, std: 0.02522, params: {'max_depth': 5, 'min_samples_split': 90},\n",
       "  mean: 0.80923, std: 0.02777, params: {'max_depth': 5, 'min_samples_split': 110},\n",
       "  mean: 0.80823, std: 0.02634, params: {'max_depth': 5, 'min_samples_split': 130},\n",
       "  mean: 0.80801, std: 0.02637, params: {'max_depth': 5, 'min_samples_split': 150},\n",
       "  mean: 0.80792, std: 0.02685, params: {'max_depth': 5, 'min_samples_split': 170},\n",
       "  mean: 0.80771, std: 0.02587, params: {'max_depth': 5, 'min_samples_split': 190},\n",
       "  mean: 0.81688, std: 0.02996, params: {'max_depth': 7, 'min_samples_split': 50},\n",
       "  mean: 0.81872, std: 0.02584, params: {'max_depth': 7, 'min_samples_split': 70},\n",
       "  mean: 0.81501, std: 0.02857, params: {'max_depth': 7, 'min_samples_split': 90},\n",
       "  mean: 0.81476, std: 0.02552, params: {'max_depth': 7, 'min_samples_split': 110},\n",
       "  mean: 0.81557, std: 0.02791, params: {'max_depth': 7, 'min_samples_split': 130},\n",
       "  mean: 0.81459, std: 0.02905, params: {'max_depth': 7, 'min_samples_split': 150},\n",
       "  mean: 0.81601, std: 0.02808, params: {'max_depth': 7, 'min_samples_split': 170},\n",
       "  mean: 0.81704, std: 0.02757, params: {'max_depth': 7, 'min_samples_split': 190},\n",
       "  mean: 0.82090, std: 0.02665, params: {'max_depth': 9, 'min_samples_split': 50},\n",
       "  mean: 0.81908, std: 0.02527, params: {'max_depth': 9, 'min_samples_split': 70},\n",
       "  mean: 0.82036, std: 0.02422, params: {'max_depth': 9, 'min_samples_split': 90},\n",
       "  mean: 0.81889, std: 0.02927, params: {'max_depth': 9, 'min_samples_split': 110},\n",
       "  mean: 0.81991, std: 0.02868, params: {'max_depth': 9, 'min_samples_split': 130},\n",
       "  mean: 0.81788, std: 0.02436, params: {'max_depth': 9, 'min_samples_split': 150},\n",
       "  mean: 0.81898, std: 0.02588, params: {'max_depth': 9, 'min_samples_split': 170},\n",
       "  mean: 0.81746, std: 0.02716, params: {'max_depth': 9, 'min_samples_split': 190},\n",
       "  mean: 0.82395, std: 0.02454, params: {'max_depth': 11, 'min_samples_split': 50},\n",
       "  mean: 0.82380, std: 0.02258, params: {'max_depth': 11, 'min_samples_split': 70},\n",
       "  mean: 0.81953, std: 0.02552, params: {'max_depth': 11, 'min_samples_split': 90},\n",
       "  mean: 0.82254, std: 0.02366, params: {'max_depth': 11, 'min_samples_split': 110},\n",
       "  mean: 0.81950, std: 0.02768, params: {'max_depth': 11, 'min_samples_split': 130},\n",
       "  mean: 0.81887, std: 0.02636, params: {'max_depth': 11, 'min_samples_split': 150},\n",
       "  mean: 0.81910, std: 0.02734, params: {'max_depth': 11, 'min_samples_split': 170},\n",
       "  mean: 0.81564, std: 0.02622, params: {'max_depth': 11, 'min_samples_split': 190},\n",
       "  mean: 0.82291, std: 0.02092, params: {'max_depth': 13, 'min_samples_split': 50},\n",
       "  mean: 0.82177, std: 0.02513, params: {'max_depth': 13, 'min_samples_split': 70},\n",
       "  mean: 0.82415, std: 0.02480, params: {'max_depth': 13, 'min_samples_split': 90},\n",
       "  mean: 0.82420, std: 0.02417, params: {'max_depth': 13, 'min_samples_split': 110},\n",
       "  mean: 0.82209, std: 0.02481, params: {'max_depth': 13, 'min_samples_split': 130},\n",
       "  mean: 0.81852, std: 0.02227, params: {'max_depth': 13, 'min_samples_split': 150},\n",
       "  mean: 0.81955, std: 0.02885, params: {'max_depth': 13, 'min_samples_split': 170},\n",
       "  mean: 0.82092, std: 0.02600, params: {'max_depth': 13, 'min_samples_split': 190}],\n",
       " {'max_depth': 13, 'min_samples_split': 110},\n",
       " 0.8242016800050813)"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "param_test2 = {'max_depth':[3,5,7,9,11,13], 'min_samples_split':[50,70,90,110,130,150,170,190]}\n",
    "gsearch2 = GridSearchCV(estimator = RandomForestClassifier(n_estimators= 60, \n",
    "                                  min_samples_leaf=20,max_features='sqrt' ,oob_score=True, random_state=10),\n",
    "   param_grid = param_test2, scoring='roc_auc',iid=False, cv=5)\n",
    "gsearch2.fit(X,y)\n",
    "gsearch2.grid_scores_, gsearch2.best_params_, gsearch2.best_score_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.984\n"
     ]
    }
   ],
   "source": [
    "rf1 = RandomForestClassifier(n_estimators= 60, max_depth=13, min_samples_split=110,\n",
    "                                  min_samples_leaf=20,max_features='sqrt' ,oob_score=True, random_state=10)\n",
    "rf1.fit(X,y)\n",
    "print (rf1.oob_score_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "([mean: 0.82093, std: 0.02287, params: {'min_samples_leaf': 10, 'min_samples_split': 80},\n",
       "  mean: 0.81913, std: 0.02141, params: {'min_samples_leaf': 10, 'min_samples_split': 100},\n",
       "  mean: 0.82048, std: 0.02328, params: {'min_samples_leaf': 10, 'min_samples_split': 120},\n",
       "  mean: 0.81798, std: 0.02099, params: {'min_samples_leaf': 10, 'min_samples_split': 140},\n",
       "  mean: 0.82094, std: 0.02535, params: {'min_samples_leaf': 20, 'min_samples_split': 80},\n",
       "  mean: 0.82097, std: 0.02327, params: {'min_samples_leaf': 20, 'min_samples_split': 100},\n",
       "  mean: 0.82487, std: 0.02110, params: {'min_samples_leaf': 20, 'min_samples_split': 120},\n",
       "  mean: 0.82169, std: 0.02406, params: {'min_samples_leaf': 20, 'min_samples_split': 140},\n",
       "  mean: 0.82352, std: 0.02271, params: {'min_samples_leaf': 30, 'min_samples_split': 80},\n",
       "  mean: 0.82164, std: 0.02381, params: {'min_samples_leaf': 30, 'min_samples_split': 100},\n",
       "  mean: 0.82070, std: 0.02528, params: {'min_samples_leaf': 30, 'min_samples_split': 120},\n",
       "  mean: 0.82141, std: 0.02508, params: {'min_samples_leaf': 30, 'min_samples_split': 140},\n",
       "  mean: 0.82278, std: 0.02294, params: {'min_samples_leaf': 40, 'min_samples_split': 80},\n",
       "  mean: 0.82141, std: 0.02547, params: {'min_samples_leaf': 40, 'min_samples_split': 100},\n",
       "  mean: 0.82043, std: 0.02724, params: {'min_samples_leaf': 40, 'min_samples_split': 120},\n",
       "  mean: 0.82162, std: 0.02348, params: {'min_samples_leaf': 40, 'min_samples_split': 140},\n",
       "  mean: 0.82225, std: 0.02431, params: {'min_samples_leaf': 50, 'min_samples_split': 80},\n",
       "  mean: 0.82225, std: 0.02431, params: {'min_samples_leaf': 50, 'min_samples_split': 100},\n",
       "  mean: 0.81890, std: 0.02458, params: {'min_samples_leaf': 50, 'min_samples_split': 120},\n",
       "  mean: 0.81917, std: 0.02528, params: {'min_samples_leaf': 50, 'min_samples_split': 140}],\n",
       " {'min_samples_leaf': 20, 'min_samples_split': 120},\n",
       " 0.8248650279471544)"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "param_test3 = {'min_samples_split':[80,100,120,140], 'min_samples_leaf':[10,20,30,40,50]}\n",
    "gsearch3 = GridSearchCV(estimator = RandomForestClassifier(n_estimators= 60, max_depth=13,\n",
    "                                  max_features='sqrt' ,oob_score=True, random_state=10),\n",
    "   param_grid = param_test3, scoring='roc_auc',iid=False, cv=5)\n",
    "gsearch3.fit(X,y)\n",
    "gsearch3.grid_scores_, gsearch3.best_params_, gsearch3.best_score_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "([mean: 0.81981, std: 0.02586, params: {'max_features': 3},\n",
       "  mean: 0.81639, std: 0.02533, params: {'max_features': 5},\n",
       "  mean: 0.82487, std: 0.02110, params: {'max_features': 7},\n",
       "  mean: 0.81704, std: 0.02209, params: {'max_features': 9}],\n",
       " {'max_features': 7},\n",
       " 0.8248650279471544)"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "param_test4 = {'max_features':[3,5,7,9]}\n",
    "gsearch4 = GridSearchCV(estimator = RandomForestClassifier(n_estimators= 60, max_depth=13, min_samples_split=120,\n",
    "                                  min_samples_leaf=20 ,oob_score=True, random_state=10),\n",
    "   param_grid = param_test4, scoring='roc_auc',iid=False, cv=5)\n",
    "gsearch4.fit(X,y)\n",
    "gsearch4.grid_scores_, gsearch4.best_params_, gsearch4.best_score_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.984\n"
     ]
    }
   ],
   "source": [
    "rf2 = RandomForestClassifier(n_estimators= 60, max_depth=13, min_samples_split=120,\n",
    "                                  min_samples_leaf=20,max_features=7 ,oob_score=True, random_state=10)\n",
    "rf2.fit(X,y)\n",
    "print (rf2.oob_score_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
